import yaml
import sys
from typing import Any
from pathlib import Path
from pydantic import ValidationError

def must_load_config(config_cls: type, file: str | Path) -> Any:
    """
    加载配置并在失败时退出程序的通用函数
    
    Args:
        config_cls: Pydantic配置类
        file: 配置文件路径(字符串或Path对象)
        
    Returns:
        成功加载的配置实例
    """
    try:
        with open(file, "r") as f:
            yaml_data = yaml.safe_load(f)
            return config_cls(**yaml_data)
    except FileNotFoundError:
        print(f"Error: Config file not found at {file}", file=sys.stderr)
        sys.exit(1)
    except yaml.YAMLError as e:
        print(f"Error: Invalid YAML format in config file: {e}", file=sys.stderr)
        sys.exit(1)
    except ValidationError as e:
        print(f"Error: Invalid configuration: {e}", file=sys.stderr)
        sys.exit(1)
    except Exception as e:
        print(f"Unexpected error loading config: {e}", file=sys.stderr)
        sys.exit(1)